package org.liaohailong.library.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * create by liaohailong
 * time 2022/8/24 17:09
 * desc:
 */
public class AppUtils {
    /**
     * 获取当前程序版本号名
     * android:versionName="2.0"
     */

    public static String getVersionName(Context context) {
        if (null == context) return "";

        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            // 不会发生的异常
            return "";
        }
    }

    /**
     * 获取当前程序版本号
     * android:versionCode="1"
     */

    public static int getVersionCode(Context context) {
        if (null == context) return 0;

        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取应用名称
     */

    public static String getApplicationName(Context context) {
        String applicationName = "ApplicationName";

        if (null != context) {
            try {
                PackageManager packageManager = context.getPackageManager();
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                int labelRes = packageInfo.applicationInfo.labelRes;
                applicationName = context.getResources().getString(labelRes);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        return applicationName;
    }
}
